package com.gxa.xiaoucomeshome.intercepter;

import com.gxa.xiaoucomeshome.exception.ExceptionCode;
import com.gxa.xiaoucomeshome.exception.BusinessException;
import com.gxa.xiaoucomeshome.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Administrator
 */
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    StringUtils stringUtils;

    /**
     * 拦截前处理
     *
     * @param httpServletRequest  request对象(header/session)
     * @param httpServletResponse response对象(转发,通过全局异常处理已经可以实现给前端的异常响应)
     * @param o                   封装的一个方法的Method对象:/user/login->login()->得到方法的信息(反射)->注解
     *                            例如:设计一个自定义注解:@NeedToken
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse, Object o) throws Exception {
        //存在就在校验token
        //前端通过header
        String token = httpServletRequest.getHeader("token");
        //服务器中存的token
        HttpSession session = httpServletRequest.getSession();
        Object sysToken = session.getAttribute("token");
        if (stringUtils.isEmpty(token)) {
            throw new BusinessException(ExceptionCode.EMPTY_TOKEN);
        } else if (!token.equals(sysToken)) {
            throw new BusinessException(ExceptionCode.WRONG_TOKEN);
        } else if (o instanceof HandlerMethod){
            return true;
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
